const mongoose = require('mongoose');

// AI对话消息模型
const aiMessageSchema = new mongoose.Schema({
  role: {
    type: String,
    enum: ['user', 'ai'],
    required: true
  },
  content: {
    type: String,
    required: true
  },
  image: {
    type: String, // base64图片数据
    default: null
  },
  model: {
    type: String,
    enum: ['ollama', 'coze'],
    default: 'ollama'
  },
  modelName: {
    type: String,
    default: null
  },
  isError: {
    type: Boolean,
    default: false
  },
  timestamp: {
    type: Date,
    default: Date.now
  }
});

// AI对话会话模型
const aiChatSessionSchema = new mongoose.Schema({
  sessionId: {
    type: String,
    required: true,
    unique: true
  },
  userId: {
    type: String,
    default: 'anonymous' // 匿名用户
  },
  title: {
    type: String,
    default: '新对话'
  },
  messages: [aiMessageSchema],
  selectedModel: {
    type: String,
    enum: ['ollama', 'coze'],
    default: 'ollama'
  },
  systemPrompt: {
    type: String,
    default: '你是一个有用的AI助手。'
  },
  temperature: {
    type: Number,
    default: 0.7
  },
  maxTokens: {
    type: Number,
    default: 2048
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  },
  isActive: {
    type: Boolean,
    default: true
  }
});

// 更新时间中间件
aiChatSessionSchema.pre('save', function(next) {
  this.updatedAt = Date.now();
  next();
});

// 创建索引
aiChatSessionSchema.index({ sessionId: 1 });
aiChatSessionSchema.index({ userId: 1 });
aiChatSessionSchema.index({ createdAt: -1 });

const AIChatSession = mongoose.model('AIChatSession', aiChatSessionSchema, 'ai_chat_sessions');

module.exports = {
  AIChatSession,
  aiMessageSchema
}; 